import { login } from '../../api/user'
import storage from '../../utils/storage'

const state = {
  token: storage.getItem('token'),
  userInfo: storage.getItem('userinfo')
}

const mutations = {
  // 更改token数据
  SET_TOKEN(state, paylod) {
    state.token = paylod
  },
  // 更改userinfo数据
  SET_USER_INFO(state, paylod) {
    state.userInfo = paylod
  }
}

const actions = {
  // 登陆请求数据
  login({ commit }, paylod) {
    // 返回promise
    return new Promise((resolve, reject) => {
      login(paylod).then(res => {
        // 通过 mutations 操作数据
        commit("SET_TOKEN", res.data.message.token)
        commit("SET_USER_INFO", res.data.message)
        // 把数据存到本地存储防止页面刷新数据丢失
        storage.setItem('token', res.data.message.token)
        storage.setItem('userinfo', res.data.message)
        resolve()
      }).catch(err => {
        // 返回异常
        reject(err)
      })
    })
  }
}

const getters = {

}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}